<template>
  <div class="address-edit-box">
    <s-header
      :title="`${data.type == 'add' ? '新增地址' : '编辑地址'}`"
    ></s-header>
    <van-address-edit
      class="edit"
      :area-list="areaList"
      :show-delete="data.type == 'edit'"
      :address-info="data.list"
      show-set-default
      show-search-result
      :search-result="data.searchResult"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
      @change-area="test"
      @change="saveItem"
    />
  </div>
</template>

<script setup lang="ts">
import sHeader from "@/components/SimpleHeader";
import { areaList } from "@vant/area-data";
import {
  getAddress,
  alertAddress,
  addAddress,
  deleteAddress,
} from "../service/address";
import { reactive, onMounted, toRaw } from "vue";
import { Toast, List } from "vant";
import { useRoute, useRouter } from "vue-router";
interface item {
  addressDetail: any;
  areaCode: string;
  city: string;
  country: string;
  county: string;
  isDefault: boolean;
  name: string;
  postalCode: string;
  province: string;
  tel: string;
}
interface data {
  areaList: string;
  searchResult: [];
  type: string;
  addressId: string;
  addressInfo: {};
  from: string;
  list: item;
}
type icon = "详细地址" | "姓名" | "电话";
type ikun = "addressDetail" | "name" | "tel";

const route = useRoute();
const router = useRouter();
const data = reactive({
  areaList: "",
  searchResult: [],
  type: route.query.type,
  addressId: "",
  addressInfo: {},
  from: "",
  list: {
    addressDetail: "",
    areaCode: "",
    city: "",
    country: "",
    county: "",
    isDefault: false,
    name: "",
    postalCode: "",
    province: "",
    tel: "",
  },
});

const onSave = async (item: item) => {
  console.log(item);
  // 发送的数据
  let sendData = {
    sname: item.name,
    phone: item.tel,
    province: item.province,
    city: item.city,
    town: item.county,
    detailaddress: `${
      data.areaList.split("/")[2] === undefined
        ? data.areaList
        : data.areaList.split("/")[2]
    }/${item.addressDetail}`,
    isdefault: Number(item.isDefault),
  };
  if (route.query.type == "add") {
    // 添加操作
    // console.log(sendData);
    const recever: any = await addAddress(sendData);
    // console.log(recever);
    setTimeout(() => {
      if (recever.code === 1000) router.go(-1);
    }, 1000);
  } else {
    // 修改操作
    let receive: any = await alertAddress(sendData, route.query.ID);
    setTimeout(() => {
      if (receive.code === 1000) router.go(-1);
    }, 1000);
  }
  Toast("保存成功");
};
const onDelete = async (item: item) => {
  let sendData = {
    sname: item.name,
    phone: item.tel,
    province: item.province,
    city: item.city,
    town: item.county,
    detailaddress: item.addressDetail,
    isdefault: Number(item.isDefault),
  };
  let delMsg: any = await deleteAddress(sendData, route.query.ID);
  // console.log(delMsg);
  setTimeout(() => {
    if (delMsg.code === 1000) router.go(-1);
  }, 1000);
  Toast.success("删除成功");
};
const test = (item: any) => {
  data.areaList = `${item[0].code}/${item[1].code}/${item[2].code}`;
  data.list.areaCode = item[2].code;
};
const saveItem = (event: any) => {
  let itemObj = {
    详细地址: "addressDetail",
    姓名: "name",
    电话: "tel",
  };
  let item = itemObj[event.target.placeholder as icon];
  data.list[item as ikun] = event.target.value;
};
async function getData() {
  if (route.query.type === "add" || localStorage.getItem("token") === null)
    return;
  Toast.loading({
    message: "加载中...",
    forbidClick: true,
  });
  let datas: any = await getAddress();
  let newList = datas.data.filter(
    (item: any) => item.ID === Number(route.query.ID)
  );
  console.log(newList);

  data.list = {
    addressDetail: newList[0].detail_address.split("/")[1],
    areaCode: newList[0].detail_address.split("/")[0] || "",
    city: newList[0].city,
    country: "",
    county: newList[0].town,
    isDefault: Boolean(newList[0].isdefault),
    name: newList[0].sname,
    postalCode: "",
    province: newList[0].province,
    tel: newList[0].phone,
  };
  data.areaList = newList[0].detail_address.split("/")[0];
  // console.log(data.list);
  Toast.clear();
}
onMounted(() => {
  getData();
});
</script>

<style lang="less" scoped>
@import "../common/style/mixin";

.address-edit-box {
  margin-top: 44px;

  .van-address-edit {
    /deep/ .van-button--danger {
      background: @primary;
      border-color: @primary;
    }

    /deep/ .van-switch--on {
      background: @primary;
    }
  }
}
</style>